export class ResourceLoader {
  private static instance: ResourceLoader;
  private loadedResources: Set<string> = new Set();

  static getInstance(): ResourceLoader {
    if (!ResourceLoader.instance) {
      ResourceLoader.instance = new ResourceLoader();
    }
    return ResourceLoader.instance;
  }

  // 预加载关键资源
  preloadCriticalResources(): void {
    const criticalResources: string[] = [
      // 可以在这里添加需要预加载的关键资源
    ];

    criticalResources.forEach(resource => {
      this.preloadResource(resource);
    });
  }

  // 预加载单个资源
  preloadResource(url: string): void {
    if (this.loadedResources.has(url)) return;

    const link = document.createElement('link');
    link.rel = 'preload';
    link.as = this.getResourceType(url);
    link.href = url;
    document.head.appendChild(link);
    this.loadedResources.add(url);
  }

  // 判断资源类型
  private getResourceType(url: string): string {
    if (url.match(/\.(jpg|jpeg|png|gif|webp)$/i)) return 'image';
    if (url.match(/\.(woff|woff2|ttf|eot)$/i)) return 'font';
    if (url.match(/\.(css)$/i)) return 'style';
    if (url.match(/\.(js)$/i)) return 'script';
    return 'fetch';
  }

  // 批量预加载图片
  preloadImages(urls: string[]): Promise<void[]> {
    const promises = urls.map(url => this.preloadImage(url));
    return Promise.all(promises);
  }

  // 预加载单个图片
  private preloadImage(url: string): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.loadedResources.has(url)) {
        resolve();
        return;
      }

      const img = new Image();
      img.onload = () => {
        this.loadedResources.add(url);
        resolve();
      };
      img.onerror = () => {
        console.warn(`Failed to preload image: ${url}`);
        resolve(); // 不阻塞其他资源加载
      };
      img.src = url;
    });
  }

  // 检查资源是否已加载
  isResourceLoaded(url: string): boolean {
    return this.loadedResources.has(url);
  }

  // 获取加载统计
  getLoadingStats(): { loaded: number; total: number } {
    return {
      loaded: this.loadedResources.size,
      total: this.loadedResources.size // 可以根据需要调整
    };
  }
} 